<template>
  <div class="min-h-screen flex flex-col items-center justify-center bg-white px-4">
    <!-- Logo区域 -->
    <div class="mb-12 text-center">
      <div class="text-5xl mb-2">🍎</div>
      <h1 class="text-3xl font-light text-gray-800">创建账号</h1>
      <p class="mt-2 text-sm text-gray-500">加入我们，开启全新体验</p>
    </div>

    <!-- 注册表单 -->
    <div class="w-full max-w-sm">
      <form @submit.prevent="handleSubmit" class="space-y-6">
        <!-- 用户名输入框 -->
        <div class="space-y-2">
          <input id="username" v-model="registerForm.username" type="text" required @blur="validateUsername"
            @input="validateUsername"
            class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-gray-300 focus:ring-0 transition-colors bg-gray-50 text-gray-800"
            :class="{ 'border-red-300 bg-red-50': errors.username }" placeholder="用户名（4-20个字符）" />
          <p v-if="errors.username" class="text-sm text-red-500 mt-1">{{ errors.username }}</p>
        </div>

        <!-- 邮箱输入框 -->
        <div class="space-y-2">
          <input id="email" v-model="registerForm.email" type="email" required @blur="validateEmail"
            @input="validateEmail"
            class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-gray-300 focus:ring-0 transition-colors bg-gray-50 text-gray-800"
            :class="{ 'border-red-300 bg-red-50': errors.email }" placeholder="电子邮箱" />
          <p v-if="errors.email" class="text-sm text-red-500 mt-1">{{ errors.email }}</p>
        </div>

        <!-- 昵称输入框 -->
        <div class="space-y-2">
          <input id="nickname" v-model="registerForm.nickname" type="text" required @blur="validateNickname"
            @input="validateNickname"
            class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-gray-300 focus:ring-0 transition-colors bg-gray-50 text-gray-800"
            :class="{ 'border-red-300 bg-red-50': errors.nickname }" placeholder="昵称（2-12个字符）" />
          <p v-if="errors.nickname" class="text-sm text-red-500 mt-1">{{ errors.nickname }}</p>
        </div>

        <!-- 密码输入框 -->
        <div class="space-y-2">
          <div class="relative">
            <input id="password" v-model="registerForm.password" :type="showPassword ? 'text' : 'password'" required
              @blur="validatePassword" @input="validatePassword"
              class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-gray-300 focus:ring-0 transition-colors bg-gray-50 text-gray-800"
              :class="{ 'border-red-300 bg-red-50': errors.password }" placeholder="密码（6-20个字符）"
              autocomplete="new-password" />
            <div class="absolute inset-y-0 right-0 pr-3 flex items-center">
              <el-icon class="cursor-pointer text-gray-400 hover:text-gray-600" @click="showPassword = !showPassword">
                <View v-if="showPassword" />
                <Hide v-else />
              </el-icon>
            </div>
          </div>
          <p v-if="errors.password" class="text-sm text-red-500 mt-1">{{ errors.password }}</p>
        </div>

        <!-- 注册按钮 -->
        <button type="submit" :disabled="loading || !isFormValid"
          class="w-full bg-black hover:bg-gray-800 text-white font-medium py-3 px-4 rounded-xl transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed">
          {{ loading ? "注册中..." : "立即注册" }}
        </button>

        <!-- 登录链接 -->
        <div class="text-center text-sm text-gray-600">
          已有账号？
          <router-link to="/login" class="text-blue-500 hover:text-blue-600 transition-colors font-medium">
            立即登录
          </router-link>
        </div>
      </form>
    </div>

    <!-- 底部信息 -->
    <div class="mt-12 text-center text-sm text-gray-500">
      <p>注册即表示您同意我们的</p>
      <div class="mt-1 space-x-2">
        <a href="#" class="text-gray-600 hover:text-gray-800 transition-colors">服务条款</a>
        <span>和</span>
        <a href="#" class="text-gray-600 hover:text-gray-800 transition-colors">隐私政策</a>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/useUserStore'
import { View, Hide } from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const showPassword = ref(false)

const registerForm = reactive({
  username: '',
  email: '',
  nickname: '',
  password: ''
})

const errors = reactive({
  username: '',
  email: '',
  nickname: '',
  password: ''
})

// 验证用户名
const validateUsername = () => {
  if (!registerForm.username) {
    errors.username = '请输入用户名'
  } else if (registerForm.username.length < 4) {
    errors.username = '用户名不能少于4个字符'
  } else if (registerForm.username.length > 20) {
    errors.username = '用户名不能超过20个字符'
  } else if (!/^[a-zA-Z0-9_]+$/.test(registerForm.username)) {
    errors.username = '用户名只能包含字母、数字和下划线'
  } else {
    errors.username = ''
  }
}

// 验证邮箱
const validateEmail = () => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!registerForm.email) {
    errors.email = '请输入邮箱地址'
  } else if (!emailRegex.test(registerForm.email)) {
    errors.email = '请输入有效的邮箱地址'
  } else {
    errors.email = ''
  }
}

// 验证昵称
const validateNickname = () => {
  if (!registerForm.nickname) {
    errors.nickname = '请输入昵称'
  } else if (registerForm.nickname.length < 2) {
    errors.nickname = '昵称不能少于2个字符'
  } else if (registerForm.nickname.length > 12) {
    errors.nickname = '昵称不能超过12个字符'
  } else {
    errors.nickname = ''
  }
}

// 验证密码
const validatePassword = () => {
  if (!registerForm.password) {
    errors.password = '请输入密码'
  } else if (registerForm.password.length < 6) {
    errors.password = '密码不能少于6个字符'
  } else if (registerForm.password.length > 20) {
    errors.password = '密码不能超过20个字符'
  } else if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(registerForm.password)) {
    errors.password = '密码必须包含大小写字母和数字'
  } else {
    errors.password = ''
  }
}

// 表单是否有效
const isFormValid = computed(() => {
  return (
    registerForm.username &&
    registerForm.email &&
    registerForm.nickname &&
    registerForm.password &&
    !errors.username &&
    !errors.email &&
    !errors.nickname &&
    !errors.password
  )
})

// 处理表单提交
const handleSubmit = async () => {
  // 提交前进行所有验证
  validateUsername()
  validateEmail()
  validateNickname()
  validatePassword()

  if (!isFormValid.value) {
    return
  }

  try {
    loading.value = true
    const response = await userStore.register(registerForm)
    ElMessage.success('注册成功')
    // 携带用户名跳转到登录页面
    router.push({
      path: '/login',
      query: {
        username: response.username
      }
    })
  } catch (error: any) {
    ElMessage.error(error.message || '注册失败')
  } finally {
    loading.value = false
  }
}
</script>